<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<h3>使用defineProperty定义属性</h3>
		<ul>
			<li>defineProperty用于为某个对象添加属性定义</li>
			<li>属性可包括get和set，set可以在赋值时对数据进行检查，从而防范一些错误的赋值</li>
			<li>_开头的变量，从约定上来说是"私有变量"，不建议直接访问；但只是约定而已，仍然可以被直接访问</li>
			<button onclick="funcTest1()">运行例子</button>
		</ul>
		<script>
			function funcTest1(){
				var person = {
					name : "jerry",
					_age : 25
				};
				Object.defineProperty(person, "age", {
					get: function(){
						return this._age;
					},
					set: function(newVal){
						if(newVal > 0 && newVal <100){
							this._age = newVal;
						}
					}
				});
				console.log(person.age);
				person.age = -1;
				console.log(person.age);
			}
		</script>
		
		<h3>遍历对象的属性</h3>
		<ul>
			<li>for-in专门用于对对象属性的遍历</li>
			<li>通过：对象名[属性名]，可以返回对象的指定属性值</li>
			<button onclick="funcTest2()">运行例子</button>
		</ul>
		<script>
			function funcTest2(){
				var person = {
					name : "jerry",
					age : 25,
					sayHello : function(){}
				};
				for(var prop in person){
					console.log(prop + ":" + person[prop]);
				}
			}
		</script>
		
		<h3>模拟私有成员</h3>
		<ul>
			<li>通过定义函数内部的局部变量，可以模拟私有成员(从函数外部无法访问函数内部的变量)</li>
			<button onclick="funcTest3()">运行例子</button>
		</ul>
		<script>
			function Person(name, gender){
				var _name = name;
				var _gender = gender;
				Person.prototype.getName = function(){
					return _name;
				};
				Person.prototype.setName = function(newName){
					_name = newName;
				};
				Person.prototype.getGender = function(){
					return _gender;
				};
				Person.prototype.setGender = function(newGender){
					_gender = newGender;
				};
			}
			
			function funcTest3(){
				var p1 = new Person("jerry", "男");
				console.log(p1.name);	//undefined
				console.log(p1._name);	//undefined
				console.log(p1.getName());	//jerry
				var p2 = new Person("jam","女");
				console.log(p2.getName());	//jam
				console.log(p1.getName());	//jam
			}
		</script>
	</body>
</html>
